<?php

namespace App\Models;

use App\Libs\DataFormat;
use Hashids\Hashids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Org extends Model
{

    use DataFormat;

    protected $table = 'org';
    protected $dates = [''];

    protected $guarded = ['id', 'created_at'];

    public static  $formatKey = [ 'name'=>'string','logo'=>'image_url', 'module_settings'=>'json_decode'];

    protected  $casts = ['custom_config'=>'array', 'wechat_message_config'=>'array'];

    public function getAllInfo()
    {
        $data = Org::format($this);
        $data['href'] = $this->getBaseUrl();
        $data['org_info_without_tags'] = strip_tags($this->org_info);
        $data['org_info'] = $this->org_info;

        return $data;
    }

    public static function getOrgInfo()
    {
        $orgCode = request()->header('X-org-code', '');

        $hashids = new Hashids('', 10);

        $orgCode = $hashids->decode($orgCode);

        $orgInfo = Org::where('id', $orgCode)->first();

        return $orgInfo;
    }

    public static function getScoreConf()
    {
        $orgInfo = Org::getOrgInfo();
        $config = json_decode($orgInfo->score_settings, true);

        $config['register'] = isset($config['register'])? $config['register']:10;
        $config['certification'] = isset($config['certification'])? $config['certification']:10;
        $config['reward_time'] = isset($config['reward_time'])? $config['reward_time']:10;
        $config['project_hire'] = isset($config['project_hire'])? $config['project_hire']:10;

        unset($config['project_hire']);

        return $config;
    }

    public function projectCount()
    {
        return Project::where('org_id', $this->id)->where('status', 1)->where('verify_status', 1)->count();
    }

    public function rewardTime()
    {
        return Volunteer::where('org_id', $this->id)->sum('reward_time');
    }


    public static function getWechatConf()
    {
        $orgInfo = Org::getOrgInfo();
        $options = config('wechat');

        if(empty($orgInfo) || empty($orgInfo->wechat_app_id) || empty($orgInfo->wechat_app_secret))
        {
            return flase;
        }

        $options['app_id'] = $orgInfo->wechat_app_id;
        $options['secret'] = $orgInfo->wechat_app_secret;
        return $options;
    }

    public function getBaseUrl()
    {
        if($this->id == 15)
        {
            return 'http://wechat.glwmb.gl.gov.cn';
        }else
        {
            return 'http://'.$this->wechat_app_id.env('BASE_HOST');
        }

    }

}
